#include "Deck.h"

bool Deck::loadFromFile(char* a_filename)
{
	Card* newCard;
	char token;
	char dummy[256];
	ifstream infile(a_filename);
	
	// Variables we want to read
	int value;
	int secondaryValue;
	char* destination;
	char* text;
	int type;

	if(!infile.is_open())
	{
		printf("File could not be opened!\n");
		return false;
	}

	while(!infile.eof())
	{
		// Read one character
		token = infile.peek();
		
		// Ignore comments and empty lines
		if(token == '#' || token == '\n' || token == '\r')
		{ 
			infile.getline(dummy, 255, '\n');
		}
		else // Found a good token!
		{
			// Clean out our temporary variables.
			value = secondaryValue = type = 0;
			destination = new char[32];
			text = new char[256];

			// Load the flavor text
			infile.getline(text, 255, '\n');
				
			// Load the type
			infile >> type;
			
			// Load the value
			if(type == CT_GOTOSPACE)
			{
				// Special case. We want the player to move to a space
				infile.get(); // Eat the extra newline
				infile.getline(destination, 32, '\n');
			}
			else
			{
				infile >> value;
				if(type == CT_PAYPERHOUSE)
				{
					infile >> secondaryValue;
				}
			}

			// Create the card and push it back						
			if(type == CT_GOTOSPACE)
				newCard = new Card(type, text, destination);
			else if(type == CT_PAYPERHOUSE)
			{
				newCard = new Card(type, text, value, secondaryValue);
			}
			else
				newCard = new Card(type, text, value);

			m_cards.push_back(*newCard);
		}
	}

	return true;
}

// Pick up the card on the top of the deck.
Card* Deck::pickUpCard()
{
	int cardReturn = topCard;

	// Start from the top of the deck if we've checked all the cards
	if(++topCard >= m_cards.size())
	{
		// TODO: Shuffle right here
		topCard = 0;
	}

	return &m_cards[cardReturn];
}